package cn.net.dckj.common.quartz;

import cn.net.dckj.common.config.Global;
import cn.net.dckj.common.utils.HttpClientUtil;
import cn.net.dckj.modules.biz.common.EducationUtils;
import cn.net.dckj.modules.biz.entity.BizSchoolCalendar;
import cn.net.dckj.modules.biz.entity.BizTeacherTimetable;
import cn.net.dckj.modules.biz.service.BizSchoolCalendarService;
import cn.net.dckj.modules.biz.service.BizTeacherTimetableService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by pan on 2017/6/23.
 */
@Service
public class TimeJob {

    @Autowired
    private BizTeacherTimetableService bizTeacherTimetableService;
    @Autowired
    private BizSchoolCalendarService bizSchoolCalendarService;

    public void doBiz() {
        System.out.println(new Date());
        /*System.out.println("第一大节课结束，虚拟机关闭启动！");
        String section = "1";
        doCloseVM(section);*/
    }

    public void doCloseVM1() {
        System.out.println("第一大节课结束，虚拟机关闭启动！");
        String section = "1";
        doCloseVM(section);
    }

    public void doCloseVM2() {
        System.out.println("第二大节课结束，虚拟机关闭启动！");
        String section = "2";
        doCloseVM(section);
    }

    public void doCloseVM3() {
        System.out.println("第三大节课结束，虚拟机关闭启动！");
        String section = "3";
        doCloseVM(section);
    }

    public void doCloseVM4() {
        System.out.println("第四大节课结束，虚拟机关闭启动！");
        String section = "4";
        doCloseVM(section);
    }

    protected void doCloseVM(String section) {
        try {
            // 确定学年和学期，查找校历
            int schoolYear = EducationUtils.getCurrentSchoolYear();
            int team = EducationUtils.getCurrentTeam();
            String err1 = "虚拟机关闭失败，原因：未查询到校历学年信息，无法确定课表！学年=" + schoolYear;
            String err2 = "虚拟机关闭失败，原因：未查询到校历学期上课开始日期信息，无法确定课表！学期=" + team;
            BizSchoolCalendar bizSchoolCalendar = new BizSchoolCalendar();
            bizSchoolCalendar.setSchoolYear(String.valueOf(schoolYear));
            List<BizSchoolCalendar> list = bizSchoolCalendarService.findList(bizSchoolCalendar);
            if (list == null || list.size() == 0) {
                System.out.println(err1);
                System.out.println("虚拟机关闭结束");
                return;
            }
            // 根据校历设置，确定学周
            int week = 0;
            if (team == 1) {
                week = EducationUtils.getCurrentSchoolWeek(list.get(0).getFirstClassStartDate());
            } else if (team == 2) {
                week = EducationUtils.getCurrentSchoolWeek(list.get(0).getSecondClassStartDate());
            }
            if (week < 1) {
                System.out.println(err2);
                System.out.println("虚拟机关闭结束");
                return;
            }
            // 确定上课星期
            int weekday = EducationUtils.getCurrentWeekDay();
            // 查找教师课表
            BizTeacherTimetable bizTeacherTimetable = new BizTeacherTimetable();
            bizTeacherTimetable.setSchoolYear(String.valueOf(schoolYear));
            bizTeacherTimetable.setTerm(String.valueOf(team));
            bizTeacherTimetable.setWeek(String.valueOf(week));
            bizTeacherTimetable.setWeekday(String.valueOf(weekday));
            bizTeacherTimetable.setSection(section);
            List<BizTeacherTimetable> teacherTimetableList = bizTeacherTimetableService.findList(bizTeacherTimetable);
            if (teacherTimetableList == null || teacherTimetableList.size() == 0) {
                System.out.println(schoolYear + "学年，第" + team + "学期，第" + week + "学周，第" + section + "大节课，无上课信息！");
                System.out.println("虚拟机关闭结束");
                return;
            }

            // 获取泽塔api登录和查询地址
            String zettaketServer = Global.getConfig("zettakit.server");
            String zettaketLoginUrl = zettaketServer + "/api/login";
            String zettaketQueryUrl = zettaketServer + "/api/compute/servers";
            // 调用登录获取token_id
            Map<String, Object> loginParams = new HashMap<String, Object>();
            loginParams.put("username", "admin");
            loginParams.put("password", "admin_pass");
            Map<String, Object> loginResult = HttpClientUtil.post(zettaketLoginUrl, loginParams);
            //Double status = (Double) mapResult.get("status");
            String loginMsg = (String) loginResult.get("msg");
            if (!"success".equals(loginMsg)) {
                System.out.println("登录泽塔失败，原因：" + loginMsg);
                System.out.println("虚拟机关闭结束");
                return;
            }
            Map tokenMap = (Map) loginResult.get("data");
            String token_id = (String) tokenMap.get("token_id");
            // 调用查询地址
            Map<String, Object> queryResult = HttpClientUtil.get(zettaketQueryUrl, null, token_id);
            String queryMsg = (String) queryResult.get("msg");
            if (!"success".equals(queryMsg)) {
                System.out.println("调用泽塔查询接口失败，原因：" + queryMsg);
                System.out.println("虚拟机关闭结束");
                return;
            }
            Map queryDataMap = (Map) queryResult.get("data");
            List<Map> queryItemList = (List<Map>) queryDataMap.get("items");
            if (queryItemList == null || queryItemList.size() < 1) {
                System.out.println("未查询到任何虚拟机信息");
                System.out.println("虚拟机关闭结束");
                return;
            }
            // 根据课表信息和查询到的虚拟机进行匹配，匹配上获取虚拟机uuid（id）并调用关机接口
            for (BizTeacherTimetable teacherTimetable : teacherTimetableList) {
                String className = teacherTimetable.getClassName() == null ? "" : teacherTimetable.getClassName();
                if (className.contains("土木")) {
                    shutdownVM(queryItemList, "土木系_学生机");
                }
                if (className.contains("建筑")) {
                    shutdownVM(queryItemList, "建筑系-学生机");
                }
                if (className.contains("环艺")) {
                    shutdownVM(queryItemList, "环艺系-学生机");
                }
                /*// 测试使用
                if (className.contains("土木")) {
                    shutdownVM(queryItemList, "hadoop");
                }*/
            }
            System.out.println("虚拟机关闭结束！");
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("虚拟机关闭失败，原因：" + e.getMessage());
            System.out.println("虚拟机关闭结束！");
        }
    }

    private void shutdownVM(List<Map> vmList, String key) {
        // 获取泽塔api停止虚拟机地址
        String zettaketServer = Global.getConfig("zettakit.server");
        String zettaketShutdownUrl = zettaketServer + "/api/compute/servers/shutdown";
        for (Map map : vmList) {
            String name = (String) map.get("OS-EXT-SRV-ATTR:hostname");
            String state = (String) map.get("OS-EXT-STS:vm_state");
            String uuid = (String) map.get("id");
            try {
                if (name.contains(key) && "active".equals(state.toLowerCase())) {
                    // 调用停止虚拟机接口
                    Map<String, Object> params = new HashMap<String, Object>();
                    params.put("server_id", uuid);
                    Map<String, Object> result = HttpClientUtil.post(zettaketShutdownUrl, params);
                    String msg = (String) result.get("msg");
                    if ("success".equals(msg)) {
                        System.out.println("虚拟机[" + name + "]关闭成功");
                    } else {
                        System.out.println("虚拟机[" + name + "]关闭失败，原因：" + msg);
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
                System.out.println("虚拟机[" + name + "]关闭失败，原因：" + e.getMessage());
            }
        }
    }
}
